package com.bgs.engineering.util;

import com.aliyuncs.exceptions.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: zl,
 * OSS工具类
 */
@Component
public class MyOSSUtil {
  private static final String endpoint = "oss-cn-beijing.aliyuncs.com";

  private static final String keyId = "LTAI5tRaGa3G5n3nPCd5WMYS";

  private static final String keySecret = "dWi0GPBsuZ8DkBSdL0zn3zZr2jrM7z";

  private static final String bucketName = "mayiservicesho";

  //OSS上传文件
  public static String uploadFile(MultipartFile file) {
    String fileName = file.getOriginalFilename();
    String folder = contentType(fileName.substring(fileName.lastIndexOf(".") + 1));
    String objectName = folder + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
    //如果没有下面这两行代码，访问url将不会预览而是直接下载下来
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setCacheControl("no-cache");
    metadata.setHeader("Pragma", "no-cache");
    metadata.setContentDisposition("inline;");
    OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
    try {
      ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()), metadata);
      String[] url = getUrl(objectName).split("\\?");
      return url[0];
    } catch (IOException e) {
      throw new ServiceException("文件上传异常！请稍后重新尝试！");
    } finally {
      if (ossClient != null) {
        ossClient.shutdown();
      }
    }
  }


  /**
   * 删除阿里云OSS服务器上的文件
   *
   * @param objectName 填写文件完整路径。文件完整路径中不能包含Bucket名称。
   * @throws ClientException
   */
  public static void deleteFile(String objectName) throws ClientException {
    //处理需要删除文件的url
    String path = dealUrl(objectName);
    EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
    try {
      // 删除文件
      ossClient.deleteObject(bucketName, path);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (ossClient != null) {
        ossClient.shutdown();
      }

    }
  }

  /**
   * 处理需要删除文件的url
   *
   * @param url
   * @return
   */
  private static String dealUrl(String url) {
    String[] split = url.split("//");
    String path = split[1].substring(split[1].indexOf("/") + 1);
    return path;
  }


  //获得URL连接
  public static String getUrl(String objectName) {
    Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
    //生成URL
    OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
    URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
    ossClient.shutdown();
    if (url != null) {
      return url.toString();
    }
    return null;
  }


  //根据文件类型分配文件夹
  private static String contentType(String fileType) {
    fileType = fileType.toLowerCase();
    String folder = "";
    switch (fileType) {
      case "bmp":
      case "gif":
      case "png":
      case "jpg":
      case "jpeg":
        folder = "images/";
        break;

      case "html":
      case "txt":
      case "xml":
        folder = "text/";
        break;

      case "map3":
        folder = "map3/";
        break;

      case "vsd":
      case "ppt":
      case "pptx":
      case "doc":
      case "docx":
      case "xls":
      case "xlsx":
      case "pdf":
        folder = "application/";
        break;
      case "mp4":
        folder = "video/";
        break;
    }
    return folder + DateTimeUtils.format("yyyyMMdd", new Date()) + '/';
  }
}
